package com.xintonghua.bussiness.ui.fragment;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Point;
import android.os.Bundle;
import android.support.design.widget.TabLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.style.ForegroundColorSpan;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSONObject;
import com.jcodecraeer.xrecyclerview.XRecyclerView;
import com.xintonghua.base.BuildConfig;
import com.xintonghua.base.ui.ImageActivity;
import com.xintonghua.base.utils.AllActivitiesHolder;
import com.xintonghua.base.utils.MyUtils;
import com.xintonghua.base.utils.RefreshUtils;
import com.xintonghua.base.widget.ConfirmDialog;
import com.xintonghua.bussiness.R;
import com.xintonghua.bussiness.adapter.GoodAdapter;
import com.xintonghua.bussiness.adapter.OrderHomeAdapter;
import com.xintonghua.bussiness.api.HttpCent;
import com.xintonghua.bussiness.api.manager.AuthManager;
import com.xintonghua.bussiness.api.myinterface.DataCallBack;
import com.xintonghua.bussiness.base.BaseFragment;
import com.xintonghua.bussiness.bean.GoodsManageBean;
import com.xintonghua.bussiness.bean.GoodsManageResponse;
import com.xintonghua.bussiness.bean.HomeTopDataBean;
import com.xintonghua.bussiness.bean.Message;
import com.xintonghua.bussiness.bean.ShopOrderListBean;
import com.xintonghua.bussiness.event.OnfreshEventBus;
import com.xintonghua.bussiness.interfaces.HomeOrderInterface;
import com.xintonghua.bussiness.request.ShopOrderListRequest;
import com.xintonghua.bussiness.ui.home.DialogMemeberSignActivity;
import com.xintonghua.bussiness.ui.home.DialogQueRenQianZiActivity;
import com.xintonghua.bussiness.ui.home.MessageActivity;
import com.xintonghua.bussiness.ui.home.SelectOrderActivity;
import com.xintonghua.bussiness.ui.home.TaskActivity;
import com.xintonghua.bussiness.ui.user.LoginActivity;
import com.xintonghua.bussiness.ui.user.SettingActivity;
import com.xintonghua.bussiness.util.JsonUtil;
import com.xintonghua.bussiness.ui.user.QRCodeActivity;
import com.xintonghua.bussiness.util.JumpUtils;
import com.xintonghua.bussiness.util.MathUtils;
import com.xintonghua.bussiness.util.MyState;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
import cn.addapp.pickers.picker.DatePicker;

/**
 * 作者：wanxianyi
 * 时间：2018/1/11.
 * 包名：com.xintonghua.bussiness.ui.fragment
 */

public class HomeFragment extends BaseFragment implements DataCallBack, InitHomeDate {
    @BindView(R.id.tv_today_task)
    TextView tvTodayTask;
    Unbinder unbinder;
    @BindView(R.id.tab_order)
    TabLayout tabOrder;
    @BindView(R.id.iv_qr_code)
    ImageView ivQrCode;
    @BindView(R.id.rl_message)
    RelativeLayout rlMessage;
    @BindView(R.id.iv_task_status)
    ImageView ivTaskStatus;
    @BindView(R.id.firstBar)
    ProgressBar firstBar;
    @BindView(R.id.lv_order)
    XRecyclerView lvOrder;
    @BindView(R.id.linearLayout)
    LinearLayout linearLayout;
    Unbinder unbinder1;
    @BindView(R.id.iv_time)
    ImageView ivTime;
    @BindView(R.id.tv_today_jihua)
    TextView tvTodayJihua;
    @BindView(R.id.ll_today_task)
    LinearLayout llTodayTask;
    @BindView(R.id.tv_benzhou_renwu)
    TextView tvBenzhouRenwu;
    @BindView(R.id.ll_week_task)
    LinearLayout llWeekTask;
    @BindView(R.id.tv_benjirenwu)
    TextView tvBenjirenwu;
    @BindView(R.id.ll_season_task)
    LinearLayout llSeasonTask;
    @BindView(R.id.tv_benyue_renwu)
    TextView tvBenyueRenwu;
    @BindView(R.id.ll_month_task)
    LinearLayout llMonthTask;
    @BindView(R.id.tv_message_count)
    TextView tvMessageCount;
    private String[] title = new String[]{"未服务", "已服务"};
    private OrderHomeAdapter adapter;
    private ShopOrderListBean response;
    private List<ShopOrderListBean.ListBean> manageBeans = new ArrayList<>();
    private int page = 1;

    private int mCurPage = 1;
    private int mCurUseStatus = 1;  //0已完成  ，1未完成（默认未完成）

    BroadcastReceiver receiver;
    HomeTopDataBean bean3;

    @Override
    public void onResume() {
        super.onResume();
        getOrderTopRenWuData();
        getOrderListData();
        HttpCent.getInstance(getActivity()).getMessageCount(this, MyState.requestFour);
    }

    @Override
    public int getLayout() {
        return R.layout.fragment_home;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        try {
            if (receiver != null)
                getActivity().unregisterReceiver(receiver);
        } catch (Exception e) {

        }
    }

    @Override
    public void initUI(View view) {
        unbinder = ButterKnife.bind(this, view);
        EventBus.getDefault().register(this);
        HttpCent.getInstance(getActivity()).shopIsUsed(this, MyState.requestFive);
//        todayTask();
        initTitle();
        initEvent();
        getActivity().registerReceiver(receiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                try {
                    getOrderListData();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }, new IntentFilter(MyState.BROAD_CASET_RECEIVER_REFRESH_HOME));
        HttpCent.getInstance(getActivity()).getMessageCount(this, MyState.requestFour);

        getOrderTopRenWuData();
    }

    //取消订单
    public void CancelOrder(String orderid) {
        HttpCent.getInstance(getActivity()).cancelOrder(orderid, this, MyState.requestTwo);
    }

    private void initTitle() {
        for (String s : title) {
            tabOrder.addTab(tabOrder.newTab().setText(s));
        }
        RefreshUtils.initList(getActivity(), lvOrder, 4, R.color.bg_color);
        adapter = new OrderHomeAdapter(getActivity(), manageBeans);

        adapter.setHomeOrderInterface(new HomeOrderInterface() {
            @Override
            public void OnCancelOrderButtonClistener(final ShopOrderListBean.ListBean bean, int position) {
                ConfirmDialog.showDialog(getActivity(), "提示", "是否取消订单？", "取消", "确定", null, new ConfirmDialog.OnRightListener() {
                    @Override
                    public void onClick(ConfirmDialog dialog) {
                        CancelOrder("" + bean.getId());
                    }
                });
            }

            @Override
            public void OnQueRenDaoDianClistener(ShopOrderListBean.ListBean bean, int position) {
                HashMap<String, String> map = new HashMap<>();
                map.put("title", "工作人员确认");
                map.put("msg", "确认后将认为客户已到店消费");
                JumpUtils.jumpActivityForResult(getActivity(), DialogQueRenQianZiActivity.class, bean, map, MyState.requestL3000, false);
            }
        });
        lvOrder.setAdapter(adapter);
        lvOrder.setLoadingListener(this);
    }


    private void initEvent() {
        tabOrder.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                if (tab.getText().equals("未服务")) {
                    page = 1;
                    mCurUseStatus = 1;
                } else if (tab.getText().equals("已服务")) {
                    page = 1;
                    mCurUseStatus = 0;
                }
                try {
                    adapter.clear();
                    adapter.notifyDataSetChanged();
                } catch (Exception e) {
                    e.printStackTrace();
                }

                getOrderListData();
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {

            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {

            }
        });
    }

    @Override
    public void solve(String result) {

    }

    private void getOrderListData() {
        ShopOrderListRequest request = new ShopOrderListRequest();
        request.setUserId(AuthManager.getId());
        request.setPageNumber(page);
        request.setPageSize(MyState.SIZE);
        request.setStatus(mCurUseStatus);
        HttpCent.getInstance(getContext()).shopOrderList("", request, this, MyState.requestOne);

    }

    @Override
    public void dataBack(Object data, int order) {
        switch (order) {
            case MyState.requestOne:
                response = JSONObject.parseObject(data.toString(), ShopOrderListBean.class);
                if (page == 1) {
                    manageBeans.clear();
                }
                manageBeans.addAll(response.getList());
                adapter.notifyDataSetChanged();
                RefreshUtils.onRefresh(adapter, lvOrder);
                break;
            case MyState.requestTwo:
                try {
                    MyUtils.mToast(getActivity(), "操作成功！");
                    getOrderListData();
                } catch (Exception e) {
                    e.printStackTrace();
                }
                break;
            case MyState.requestThree:
                try {
                    bean3 = JsonUtil.getEntityByJsonString(data.toString(), HomeTopDataBean.class);
                    initHomeRenwuData(bean3);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                break;
            case MyState.requestFour:
                Message message = JSONObject.parseObject((String) data, Message.class);
                tvMessageCount.setVisibility(message.getCount() > 0 ? View.VISIBLE : View.GONE);
                tvMessageCount.setText(message.getCount() + "");
                Log.e("message", data.toString());
                break;
            case MyState.requestFive:

                break;
        }
    }

    @Override
    public void errorBack(String error, int order) {
        switch (order) {
            case MyState.requestFive:
                AllActivitiesHolder.finishAllAct();
                MyUtils.openActivity(getActivity(), LoginActivity.class);
                try {
                    AuthManager.destroy(getActivity());
                } catch (Exception e) {
                    e.printStackTrace();
                }
                break;
        }
    }

    @Override
    public void finishBack() {

    }


    @Override
    public void onStart() {
        super.onStart();
        tabOrder.post(new Runnable() {
            @Override
            public void run() {
                MyUtils.setTabLine(getContext(), tabOrder, 20, 20);
            }
        });
    }


    @OnClick({R.id.ll_today_task, R.id.ll_week_task, R.id.ll_month_task, R.id.ll_season_task, R.id.iv_qr_code, R.id.iv_message, R.id.iv_time})
    public void onViewClicked(View view) {
        Bundle bundle;
        Intent intent = new Intent(getActivity(), TaskActivity.class);
        switch (view.getId()) {
            case R.id.ll_today_task:
                intent.putExtra("taskType", "0");
                intent.putExtra("taskName", "今日目标");
                intent.putExtra("money", bean3.getThisDay());
                startActivity(intent);
                break;
            case R.id.ll_week_task:
                intent.putExtra("taskType", "1");
                intent.putExtra("taskName", "本周目标");
                intent.putExtra("money", MathUtils.strMul2(bean3.getThisWeek(), "1", 2));
                startActivity(intent);
                break;
            case R.id.ll_month_task:
                intent.putExtra("taskType", "2");
                intent.putExtra("taskName", "本月目标");
                intent.putExtra("money", bean3.getThisMonth());
                startActivity(intent);
                break;
            case R.id.ll_season_task:
                intent.putExtra("taskType", "3");
                intent.putExtra("taskName", "本季目标");
                intent.putExtra("money", bean3.getThisJidu());
                startActivity(intent);
                break;
            case R.id.iv_qr_code:
                MyUtils.openActivity(getActivity(), QRCodeActivity.class);
                break;
            case R.id.rl_message:
            case R.id.iv_message:
                MyUtils.openActivity(getActivity(), MessageActivity.class);
                break;
            //时间选择器
            case R.id.iv_time:
                onYearMonthDayPicker(view);
                break;
        }
    }

    public void onYearMonthDayPicker(View view) {
        Calendar calendar = Calendar.getInstance();
        int year = calendar.get(Calendar.YEAR);
        int month = calendar.get(Calendar.MONTH) + 1;
        int day = calendar.get(Calendar.DAY_OF_MONTH);
        final DatePicker picker = new DatePicker(getActivity());
        picker.setCanLoop(true);
        picker.setWheelModeEnable(true);
        picker.setTopPadding(15);
        picker.setRangeStart(1790, 8, 29);
        picker.setRangeEnd(2111, 1, 11);
        picker.setSelectedItem(year, month, day);
        picker.setWeightEnable(true);
        picker.setOnDatePickListener(new DatePicker.OnYearMonthDayPickListener() {
            @Override
            public void onDatePicked(String year, String month, String day) {
                Bundle bundle = new Bundle();
                bundle.putString(BuildConfig.FLAVOR, year + "-" + month + "-" + day);
                MyUtils.openActivity(getActivity(), SelectOrderActivity.class, bundle);
            }
        });
        picker.setOnWheelListener(new DatePicker.OnWheelListener() {

            @Override
            public void onYearWheeled(int index, String year) {
                picker.setTitleText(year + "-" + picker.getSelectedMonth() + "-" + picker.getSelectedDay());
            }

            @Override
            public void onMonthWheeled(int index, String month) {
                picker.setTitleText(picker.getSelectedYear() + "-" + month + "-" + picker.getSelectedDay());
            }

            @Override
            public void onDayWheeled(int index, String day) {
                picker.setTitleText(picker.getSelectedYear() + "-" + picker.getSelectedMonth() + "-" + day);
            }
        });
        picker.show();
    }

    @Override
    public void getOrderTopRenWuData() {
        HttpCent.getInstance(getActivity()).getHomeData(this, MyState.requestThree);
    }

    int querendaodianpostion = -1;

    public void QueRenToDian(getHomeFragmentData get) {
        if (querendaodianpostion >= 0) {
            get.getData(adapter.getList().get(querendaodianpostion));
        }
    }

    interface getHomeFragmentData {
        void getData(ShopOrderListBean.ListBean bean);
    }


    /**
     * 今日任务
     */
    private void todayTask(String ddy) {
        String money = ddy;
        SpannableString task = new SpannableString(money);
        task.setSpan(new ForegroundColorSpan(getResources().getColor(R.color.red)), 4, money.indexOf("/"), Spanned.SPAN_INCLUSIVE_INCLUSIVE);
        task.setSpan(new ForegroundColorSpan(getResources().getColor(R.color.grey)), money.indexOf("/"), money.length(), Spanned.SPAN_INCLUSIVE_INCLUSIVE);
        //task.setSpan(new AbsoluteSizeSpan(MyUtils.dip2px(getActivity(), 10)), 4, money.length(), Spanned.SPAN_INCLUSIVE_INCLUSIVE);
        tvTodayTask.setText(task);
    }

    @Override
    public void initHomeRenwuData(HomeTopDataBean bean) {

        firstBar.setProgress((int) Double.parseDouble(bean.getTodayOk()));
        String ddk = "今日目标" + "¥" + bean.getTodayOk() + "/" + "¥" + bean.getThisDay();
        todayTask(ddk);
        if (firstBar.getProgress() >= 100) {
            ivTaskStatus.setImageDrawable(getResources().getDrawable(R.drawable.finish));
        } else {
            ivTaskStatus.setImageDrawable(getResources().getDrawable(R.drawable.order_status));
        }
        tvTodayJihua.setText("¥" + bean.getThisDay());
        tvBenzhouRenwu.setText("¥" + MathUtils.strMul2(bean.getThisWeek(), "1", 2));
        tvBenjirenwu.setText("¥" + bean.getThisMonth());
        tvBenyueRenwu.setText("¥" + bean.getThisMonth());
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(OnfreshEventBus eventBus) {
        getOrderListData();
    }

    @Override
    public void onRefresh() {
        page = 1;
        getOrderListData();
        getOrderTopRenWuData();
        HttpCent.getInstance(getActivity()).getMessageCount(this, MyState.requestFour);

    }

    @Override
    public void onLoadMore() {
        if (RefreshUtils.hasNext(response, adapter, lvOrder)) {
            page++;
            getOrderListData();
        }
    }
}


interface InitHomeDate {
    void getOrderTopRenWuData();

    void initHomeRenwuData(HomeTopDataBean bean);
}